package defs

import (
	"net/http"
	"encoding/json"
)

const (
	OK             = 0    //成功
	NormalErr      = -1   //普通错误
	EncodeErr      = -2   //编码错误
	ParameterErr   = -3   //参数错误
	ExistErr       = -4   //存在错误
	VerifyErr      = -5   //验证错误
	TooManyErr     = -6   //太多请求错误
	SessionLoseErr = -100 //Session失效错误
	InternalErr    = 500  //内部错误
)

type ResultData struct {
	Code     int32       `json:"code"`
	Msg      string      `json:"msg"`
	DebugMeg string      `json:"debugMeg"`
	Data     interface{} `json:"data"`
}

func (r *ResultData) Error() string {
	return r.Msg
}
func NewResultData(data interface{}) *ResultData {
	return &ResultData{Code: OK, Data: data}
}
func NewResultError(code int32, meg string) *ResultData {
	return &ResultData{Code: code, Msg: meg, Data: nil}
}
func (r *ResultData) SetDebugMeg(msg string) *ResultData {
	r.DebugMeg = msg
	return r
}
func (r *ResultData) WriterResponse(w http.ResponseWriter) {
	bytes, err := json.Marshal(r)
	if err != nil {
		NewResultError(EncodeErr, "编码错误").WriterResponse(w)
		return
	}
	w.Write(bytes)
}
